﻿namespace Yewan.Modbus
{
    public static class ByteOrderHelper
    {
        /// <summary>
        /// 转换字节序
        /// </summary>
        /// <param name="data"></param>
        /// <param name="byteOrderType"></param>
        /// <returns></returns>
        public static byte[] SwitchByteOrder(ReadOnlySpan<byte> data, ByteOrderType byteOrderType)
        {
            Span<byte> result = data.Length <= 256 ? stackalloc byte[data.Length] : new byte[data.Length];
            data.CopyTo(result);

            switch (byteOrderType)
            {
                case ByteOrderType.CDAB when data.Length == 4:
                    (result[0], result[1], result[2], result[3]) = (data[2], data[3], data[0], data[1]);
                    break;

                case ByteOrderType.BADC when data.Length == 4:
                    (result[0], result[1], result[2], result[3]) = (data[1], data[0], data[3], data[2]);
                    break;

                case ByteOrderType.GHEFCDAB when data.Length == 8:
                    data.Slice(0, 4).CopyTo(result[4..]);
                    data.Slice(4, 4).CopyTo(result[0..]);
                    break;

                case ByteOrderType.BADCFEHG when data.Length == 8:
                    for (int i = 0; i < 4; i++)
                    {
                        result[i * 2] = data[i * 2 + 1];
                        result[i * 2 + 1] = data[i * 2];
                    }
                    break;

                case ByteOrderType.DCBA:
                case ByteOrderType.HGFEDCBA:
                    result.Reverse();
                    break;

                case ByteOrderType.ABCD:
                default:
                    break;
            }

            return result.ToArray();
        }

    }
}
